# analysis/device_analysis.py
from pyspark.sql import DataFrame


class DeviceAnalyzer:
    @staticmethod
    def analyze_device_performance(df: DataFrame) -> DataFrame:
        return (df
                .groupBy("device_type")
                .agg({"visits": "sum",
                      "bounce_rate": "avg",
                      "avg_session_duration": "avg",
                      "conversion_rate": "avg"})
                .withColumnRenamed("sum(visits)", "total_visits")
                .withColumnRenamed("avg(bounce_rate)", "avg_bounce_rate")
                .withColumnRenamed("avg(avg_session_duration)", "avg_session_duration")
                .withColumnRenamed("avg(conversion_rate)", "avg_conversion_rate")
                .orderBy("total_visits", ascending=False))

    @staticmethod
    def analyze_device_by_source(df: DataFrame) -> DataFrame:
        return (df
                .groupBy("device_type", "traffic_source")
                .agg({"visits": "sum"})
                .withColumnRenamed("sum(visits)", "total_visits")
                .orderBy("device_type", "total_visits", ascending=False))